<template>
  <div class="clipboard-access">
    <n-form :model="accessForm" label-placement="top">
      <n-form-item label="分享ID" path="shareId">
        <n-input
          v-model:value="accessForm.shareId"
          placeholder="输入8位分享ID"
          @keyup.enter="handleAccess"
        />
      </n-form-item>
      
      <n-form-item label="密码" path="password">
        <n-input
          v-model:value="accessForm.password"
          type="password"
          placeholder="访问密码或管理员密码（如有）"
          show-password-on="click"
          @keyup.enter="handleAccess"
        />
      </n-form-item>

      <n-button 
        type="primary" 
        block 
        size="large"
        @click="handleAccess"
        :disabled="!accessForm.shareId"
        :loading="loading"
      >
        访问剪贴板
      </n-button>
    </n-form>

    <!-- 最近访问记录 -->
    <n-card v-if="recentClipboards.length > 0" title="最近访问" style="margin-top: 24px;">
      <n-list hoverable clickable>
        <n-list-item
          v-for="item in recentClipboards"
          :key="item.id"
          @click="quickAccess(item)"
        >
          <n-thing>
            <template #header>
              <n-space>
                <n-text strong>{{ item.shareId }}</n-text>
                <n-tag v-if="item.isAdmin" type="error" size="small">管理员</n-tag>
              </n-space>
            </template>
            <template #description>
              <n-text depth="3">
                最后访问：{{ formatTime(item.lastAccessAt) }}
              </n-text>
            </template>
          </n-thing>
          <template #suffix>
            <n-button-group size="small">
              <n-button @click.stop="quickAccess(item)">访问</n-button>
              <n-button @click.stop="deleteRecord(item.id)">删除</n-button>
            </n-button-group>
          </template>
        </n-list-item>
      </n-list>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import { clipboardStorage, type ClipboardRecord } from '../utils/clipboardStorage'
import { getClipboard } from '@/api/utility/clipboard'

const emit = defineEmits<{
  'open-tab': [shareId: string]
}>()

const message = useMessage()
const loading = ref(false)

// 访问表单
const accessForm = reactive({
  shareId: '',
  password: ''
})

// 最近访问记录
const recentClipboards = ref<ClipboardRecord[]>([])


// 格式化时间
const formatTime = (timestamp: number): string => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor(diff / (1000 * 60))
  
  if (days > 0) {
    return `${days}天前`
  } else if (hours > 0) {
    return `${hours}小时前`
  } else if (minutes > 0) {
    return `${minutes}分钟前`
  } else {
    return '刚刚'
  }
}

// 访问剪贴板
const handleAccess = async () => {
  if (!accessForm.shareId.trim()) {
    message.warning('请输入分享ID')
    return
  }

  loading.value = true
  try {
    // 先调用API预检查，确认能获取到剪贴板数据
    const data = await getClipboard({
      shareId: accessForm.shareId,
      password: accessForm.password || undefined
    })
    
    // 如果能成功获取，记录访问历史
    await clipboardStorage.saveAccessHistory(accessForm.shareId)
    
    // 保存或更新IndexedDB记录 - 用户输入的密码直接覆盖
    const existingRecord = await clipboardStorage.getClipboardByShareId(accessForm.shareId)
    if (existingRecord) {
      await clipboardStorage.updateClipboard(existingRecord.id, {
        lastAccessAt: Date.now(),
        isAdmin: data.isAdmin || false,
        // 用户输入的密码直接覆盖IndexedDB中的记录
        adminPassword: data.isAdmin ? accessForm.password : undefined,
        accessPassword: !data.isAdmin ? accessForm.password : undefined
      })
    } else {
      await clipboardStorage.saveClipboard({
        shareId: accessForm.shareId,
        // 用户输入的密码直接保存
        adminPassword: data.isAdmin ? accessForm.password : undefined,
        accessPassword: !data.isAdmin ? accessForm.password : undefined,
        title: accessForm.shareId,
        createdAt: Date.now(),
        lastAccessAt: Date.now(),
        isAdmin: data.isAdmin || false
      })
    }
    
    // 打开新标签页，密码已保存在IndexedDB中
    emit('open-tab', accessForm.shareId)
    
    // 清空表单
    accessForm.shareId = ''
    accessForm.password = ''
    
    // 刷新最近访问列表
    await loadRecentClipboards()
    
    message.success('访问成功')
  } catch (error: any) {
    message.error(error.message || '访问失败')
  } finally {
    loading.value = false
  }
}

// 快速访问
const quickAccess = (item: ClipboardRecord) => {
  // 直接打开标签页，密码已在IndexedDB中
  emit('open-tab', item.shareId)
  
  // 更新最后访问时间
  clipboardStorage.updateClipboard(item.id, {
    lastAccessAt: Date.now()
  })
}

// 删除记录
const deleteRecord = async (id: string) => {
  try {
    await clipboardStorage.deleteClipboard(id)
    message.success('删除成功')
    await loadRecentClipboards()
  } catch (error) {
    message.error('删除失败')
  }
}

// 加载最近访问的剪贴板
const loadRecentClipboards = async () => {
  try {
    recentClipboards.value = await clipboardStorage.getAllClipboards()
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 设置shareId（供外部调用）
const setShareId = (shareId: string) => {
  accessForm.shareId = shareId
}

// 暴露方法给父组件
defineExpose({
  setShareId
})

// 初始化
onMounted(() => {
  loadRecentClipboards()
})
</script>

<style scoped lang="less">
.clipboard-access {
  max-width: 600px;
  margin: 0 auto;
  padding: 24px 0;

  :deep(.n-form-item) {
    margin-bottom: 16px;
  }
}

@media (max-width: 768px) {
  .clipboard-access {
    padding: 16px 0;
    
    :deep(.n-form-item) {
      margin-bottom: 12px;
    }
  }
}
</style>